package com.scrx.ymg.dao.agent;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;

import com.scrx.ymg.dao.base.BaseDaoImpl;
import com.scrx.ymg.entity.AgentHot;
import com.scrx.ymg.entity.AgentInfo;
import com.scrx.ymg.entity.AgentMoney;
import com.scrx.ymg.entity.BankAccount;
import com.scrx.ymg.entity.HeadWithdarw;
import com.scrx.ymg.entity.OtherInfo;
import com.scrx.ymg.entity.OtherMoney;
import com.scrx.ymg.entity.SuperMarketEntrepot;
import com.scrx.ymg.entity.SuperMarketInfo;
import com.scrx.ymg.entity.UserComplain;
import com.scrx.ymg.util.BaseUtil;
import com.scrx.ymg.util.LatLonUtil;

@Repository("agentInfoDao")
@Transactional(rollbackFor={Exception.class})
public class AgentInfoDaoImpl extends BaseDaoImpl implements IAgentInfoDao {

	public AgentInfo getAgentInfoByID(int agentID) {
		Query query = getCurrentSession().createQuery("from AgentInfo where id=?");
		query.setParameter(0, agentID);
		AgentInfo agentInfo = (AgentInfo) query.uniqueResult();
		return agentInfo;
	}

	public String saveAgentHot(AgentHot hot) {
		try {
			getCurrentSession().save(hot);
			return "true";
		} catch (Exception e) {
			return "false";
		}

	}

	public String saveAgentHot(AgentHot hot, MultipartFile Thumbnail, String ThumbnailPath, MultipartFile banner,
			String bannerPath,MultipartFile hotDetailFile,String hotDetailFilePath,MultipartFile bigpicFile,String bigpicPaht) {
		try {
			getCurrentSession().save(hot);
			// 转存文件
			hotDetailFile.transferTo(new File(hotDetailFilePath));
			Thumbnail.transferTo(new File(ThumbnailPath));
			banner.transferTo(new File(bannerPath));
			bigpicFile.transferTo(new File(bigpicPaht));
			return "true";
		} catch (Exception e) {
			e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return "false";
		}

	}

	public AgentHot selectAgentHot(int hotId) {
		Query query = getCurrentSession().createQuery("from AgentHot where id=?");
		query.setParameter(0, hotId);
		return (AgentHot) query.uniqueResult();
	}
    

	public String delectAgentHot(AgentHot hot) {

		try {
			getCurrentSession().delete(hot);
			return "true";
		} catch (Exception e) {
			return "false";
		}
	}

	public Map<Object, Object> selectAgentHot(AgentHot hot, int pageNum, int pageCount) {
		try {

			Map<Object, Object> map = new HashMap<Object, Object>();
			LatLonUtil util = new LatLonUtil();

			StringBuffer hql = new StringBuffer("from AgentHot where 1=1 ");
			util.init(hot.getAgentId(), "agentId", hql);
			util.init(hot.getChecka(), "checka", hql);
			hql.append(" order by submitTime");
			Query query = getCurrentSession().createQuery(hql.toString());
			List<AgentHot> hotlists = query.list();
			query.setMaxResults(pageCount);// 每页多少条
			query.setFirstResult((pageNum - 1) * pageCount);// 第几页
			List<AgentHot> hotlist = query.list();

			map.put("hotlist", hotlist);
			map.put("totalpage", (hotlists.size() + pageCount - 1) / pageCount);
			return map;
		} catch (Exception e) {
			return null;
		}

	}
	public Map<Object, Object> selectAgentHotHead(AgentHot hot, int pageNum, int pageCount) {
		try {

			Map<Object, Object> map = new HashMap<Object, Object>();
			LatLonUtil util = new LatLonUtil();

			StringBuffer hql = new StringBuffer("from AgentHot where 1=1 ");
			util.init(hot.getAgentId(), "agentId", hql);
			util.init(hot.getChecka(), "checka", hql);
			hql.append(" order by submitTime");
			Query query = getCurrentSession().createQuery(hql.toString());
			List<AgentHot> hotlists = query.list();
			query.setMaxResults(pageCount);// 每页多少条
			query.setFirstResult((pageNum - 1) * pageCount);// 第几页
			List<AgentHot> hotlist = query.list();
			AgentInfo info =null;
			for (int i = 0; i < hotlist.size(); i++) {
				 info = getAgentInfoByID(hotlist.get(i).getAgentId());
				 if(info!=null){
					 hotlist.get(i).setAgentName(info.getAgentName());
				 }
				
			}

			map.put("hotlist", hotlist);
			map.put("totalpage", (hotlists.size() + pageCount - 1) / pageCount);
			return map;
		} catch (Exception e) {
			return null;
		}

	}

	public SuperMarketInfo superNameExists(String superName) {
		try {
			Query query = getCurrentSession().createQuery("from SuperMarketInfo where name=? ");
			query.setParameter(0, superName);
			if (query.uniqueResult() != null) {
				return (SuperMarketInfo) query.uniqueResult();
			}
			return null;
		} catch (Exception e) {
			return null;
		}

	}

	@Override
	public SuperMarketInfo accountExists(String account) {
		try {
			Query query = getCurrentSession().createQuery("from SuperMarketInfo where account=? ");
			query.setParameter(0, account);
			if (query.uniqueResult() != null) {
				return (SuperMarketInfo) query.uniqueResult();
			}
			return null;
		} catch (Exception e) {
			return null;
		}
	}

	public String updateAgentHot(AgentHot hot, MultipartFile thumbnail, String thumbnailPath, MultipartFile banner,
			String bannerPath,MultipartFile hotDetailFile,String hotDetailFilePath,MultipartFile bigpicFile,String bigpicFilePath) {

		try {
			getCurrentSession().update(hot);
			if (hotDetailFile.getSize() > 0) {
				hotDetailFile.transferTo(new File(hotDetailFilePath));
			}
			if (thumbnail.getSize() > 0) {
				thumbnail.transferTo(new File(thumbnailPath));
			}
			if (banner.getSize() > 0) {
				banner.transferTo(new File(bannerPath));
			}
			if (bigpicFile.getSize() > 0) {
				bigpicFile.transferTo(new File(bigpicFilePath));
			}
			return "true";
		} catch (Exception e) {
			e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return "false";
		}
	}
	public String updateAgentHot(AgentHot hot){
		try {
			getCurrentSession().update(hot);
			return "true";
		} catch (Exception e) {
			return "false";
		}
	}

	public String updateAgentInfo(AgentInfo info) {
		try {
			getCurrentSession().update(info);
			return "true";
		} catch (Exception e) {
			return "false";
		}
	}

	public Map<Object, Object> getSuperMarketInfoList(SuperMarketInfo info, int pageNum, int pageCount) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			LatLonUtil util = new LatLonUtil();
			StringBuffer hql = new StringBuffer("from SuperMarketInfo where 1=1 ");
			util.init(info.getId(), "id", hql);
			util.init(info.getName(), "name", hql);
			util.init(info.getPhone(), "phone", hql);
			util.init(info.getAgentId(), "agentId", hql);
			util.init(info.getAgentRegion(), "agentRegion", hql);
			Query query = getCurrentSession().createQuery(hql.toString());
			List<SuperMarketInfo> listinfo = query.list();
			query.setMaxResults(pageCount);// 每页多少条
			query.setFirstResult((pageNum - 1) * pageCount);// 第几页
			List<SuperMarketInfo> list = query.list();
			double sumMoney=0.0;
			for (int i = 0; i < list.size(); i++) {
				//统计退货总数
				list.get(i).setReturnNum(getReturnOrderFormNum(list.get(i).getId()));
				list.get(i).setComplainNum(getOrderComplainNum(list.get(i).getId()));
				//统计总金额
				list.get(i).setTotalMoney(getTotalMoney(list.get(i).getId()));
				sumMoney+=getTotalMoney(list.get(i).getId());
			}
			map.put("list", list);
			map.put("sumMoney", sumMoney);
			map.put("totalpage", (listinfo.size() + pageCount - 1) / pageCount);
			return map;
		} catch (RuntimeException re) {
			throw re;
		}
	}

	public AgentMoney getAgentMoneyInfo(int agentId) {
		try {
			Query query = getCurrentSession().createQuery("from AgentMoney where agentId=?");
			query.setParameter(0, agentId);
			return (AgentMoney) query.uniqueResult();
		} catch (Exception e) {
			return null;
		}
	}


	public Map<Object, Object> getUserComplaint(UserComplain complain,String startTime,String endTime, int pageNum, int pageCount) {
		try {

			Map<Object, Object> map = new HashMap<Object, Object>();
			LatLonUtil util = new LatLonUtil();

			StringBuffer hql = new StringBuffer("from UserComplain where 1=1 ");
			util.init(complain.getSuperId(), "superId", hql);
			util.initEndDateTime(endTime, "complainTime", hql);
			util.initStartDateTime(startTime, "complainTime", hql);
			hql.append(" order by complainTime");
			Query query = getCurrentSession().createQuery(hql.toString());
			query.setMaxResults(pageCount);// 每页多少条
			query.setFirstResult((pageNum - 1) * pageCount);// 第几页
			List<UserComplain> list = query.list();
			map.put("list", list);
			map.put("totalpage", (list.size() + pageCount - 1) / pageCount);
			return map;
		} catch (Exception e) {
			return null;
		}
	}


	public AgentHot getHotProduct(int hotId) {

		try {
			Query query = getCurrentSession().createQuery("from AgentHot where id=?");
			query.setParameter(0, hotId);
			return (AgentHot) query.uniqueResult();
		} catch (Exception e) {
			return null;
		}
	}


	public Map<Object, Object> statisticsSuperMarketInfo(SuperMarketInfo info, int pageNum, int pageCount) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			LatLonUtil util = new LatLonUtil();
			StringBuffer hql = new StringBuffer("from SuperMarketInfo where 1=1 ");
			util.init(info.getName(), "name", hql);
			util.init(info.getPhone(), "phone", hql);
			util.init(info.getAgentId(), "agentId", hql);
			Query query = getCurrentSession().createQuery(hql.toString());
			List<SuperMarketInfo> listinfo = query.list();
			query.setMaxResults(pageCount);// 每页多少条
			query.setFirstResult((pageNum - 1) * pageCount);// 第几页
			List<SuperMarketInfo> list = query.list();
			
			for (int i = 0; i < list.size(); i++) {
				//统计订单数
				list.get(i).setOrderNum(getOrderFormNum(list.get(i).getId()));
				//统计会员总数
				list.get(i).setUserNum(getUserNum(list.get(i).getId()));
				//统计总金额
				list.get(i).setTotalMoney(getTotalMoney(list.get(i).getId()));
			}
			map.put("list", list);
			map.put("totalpage", (listinfo.size() + pageCount - 1) / pageCount);
			return map;
		} catch (RuntimeException re) {
			throw re;
		}
	}
	/**
	 * 超市订单总数
	 * @param super_id
	 * @return
	 */
	public int getOrderFormNum(int super_id){
	Query	query = getCurrentSession().createQuery("select COUNT(*) from OrderForm where super_id=? and typeId=1");
	query.setParameter(0, super_id);
	Iterator iter = query.iterate();
	int num=0;
	while(iter.hasNext()){
		num=((Long)iter.next()).intValue();
	};
	return num;
	}
	/**
	 * 超市退货总数
	 * @param super_id
	 * @return
	 */
	public int getReturnOrderFormNum(int super_id){
		Query	query = getCurrentSession().createQuery("select COUNT(*) from OrderForm where super_id=? and status=5 and typeId=1");
		query.setParameter(0, super_id);
		Iterator iter = query.iterate();
		int num=0;
		while(iter.hasNext()){
			num=((Long)iter.next()).intValue();
		};
		return num;
		}
	public int getOrderComplainNum(int super_id){
		Query	query = getCurrentSession().createQuery("select COUNT(*) from OrderForm where super_id=? and status=7 and typeId=1");
		query.setParameter(0, super_id);
		Iterator iter = query.iterate();
		int num=0;
		while(iter.hasNext()){
			num=((Long)iter.next()).intValue();
		};
		return num;
		}
	/**
	 * 超市会员总数
	 * @param super_id
	 * @return
	 */
	public int getUserNum(int super_id){
		Query	query = getCurrentSession().createQuery("select COUNT(*) from User where belongSupermarket=?");
		query.setParameter(0, super_id);
		Iterator iter = query.iterate();
		int num=0;
		while(iter.hasNext()){
			num=((Long)iter.next()).intValue();
		};
		return num;
	}
	
	/**
	 * 超市总金额
	 * @param super_id
	 * @return
	 */
	public double getTotalMoney(int super_id){
		Query	query = getCurrentSession().createQuery("select superMoney from SupermarketMoney where super_id=?");
		query.setParameter(0, super_id);
		Iterator iter = query.iterate();
		double num=0;
		while(iter.hasNext()){
			Object obj =iter.next();
			num=Double.parseDouble(obj.toString());
		};
		return num;
	}


	public String addAgentInfo(AgentInfo info,AgentMoney money) {
		try {
			getCurrentSession().save(info);
			money.setAgentId(info.getId());
			getCurrentSession().save(money);
			return "true";
		} catch (Exception e) {
			e.printStackTrace();
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return "false";
		}
	}


	public Map<Object, Object> selectAgentInfoList(AgentInfo info, int pageNum, int pageCount) {
		try {
			Map<Object, Object> map = new HashMap<Object, Object>();
			LatLonUtil util = new LatLonUtil();
			StringBuffer hql = new StringBuffer("from AgentInfo where 1=1 ");
			util.init(info.getAgentName(), "agentName", hql);
			util.init(info.getPhone(), "phone", hql);
			util.init(info.getAgentRegion(), "agentRegion", hql);
			util.init(info.getStatus(), "status", hql);
			Query query = getCurrentSession().createQuery(hql.toString());
			List<AgentInfo> listinfo = query.list();
			query.setMaxResults(pageCount);// 每页多少条
			query.setFirstResult((pageNum - 1) * pageCount);// 第几页
			List<AgentInfo> list = query.list();
			for (int i = 0; i < list.size(); i++) {
				//统计金额
				list.get(i).setTotalmoney(getAgentTotalMoney(list.get(i).getId()));
				list.get(i).setUserNum(getUserNumHead(list.get(i).getId()));
				list.get(i).setOrderFormNum(getOrderFormNumHead(list.get(i).getId()));
				
			}
			map.put("list", list);
			map.put("totalpage", (listinfo.size() + pageCount - 1) / pageCount);
			return map;
		} catch (RuntimeException re) {
			throw re;
		}
	}
	
	/**
	 * 代理商订单总数
	 * @param super_id
	 * @return
	 */
	public int getOrderFormNumHead(int agentId){
	Query	query = getCurrentSession().createQuery("select COUNT(*) from OrderForm where agentId=?");
	query.setParameter(0, agentId);
	Iterator iter = query.iterate();
	int num=0;
	while(iter.hasNext()){
		num=((Long)iter.next()).intValue();
	};
	return num;
	}
	/**
	 * 代理商会员总数
	 * @param super_id
	 * @return
	 */
	public int getUserNumHead(int agentId){
		Query	query = getCurrentSession().createQuery("select COUNT(*) from User where agentId=?");
		query.setParameter(0, agentId);
		Iterator iter = query.iterate();
		int num=0;
		while(iter.hasNext()){
			num=((Long)iter.next()).intValue();
		};
		return num;
	}

	/**
	 * 代理商总金额
	 * @param super_id
	 * @return
	 */
	public double getAgentTotalMoney(int agentId){
		Query	query = getCurrentSession().createQuery("select totalMoney from AgentMoney where agentId=?");
		query.setParameter(0, agentId);
		Iterator iter = query.iterate();
		double num=0;
		while(iter.hasNext()){
			Object obj =iter.next();
			num=Double.parseDouble(obj.toString());
		};
		return num;
	}


	public AgentInfo getAgentInfoByagentRegion(String agentRegion) {
		Query query = getCurrentSession().createQuery("from AgentInfo where agentRegion=?");
		query.setParameter(0, agentRegion);
		return (AgentInfo) query.uniqueResult();
	}


	public HeadWithdarw selectHeadWithdarw() {
		Query query = getCurrentSession().createQuery("from HeadWithdarw where id=1");
		return (HeadWithdarw) query.uniqueResult();
	}


	public String updateHeadWithdarw(HeadWithdarw head) {
         try {
			this.getCurrentSession().update(head);
			return "true";
		} catch (Exception e) {
			return "false";
		}
		
	}


	public OtherInfo OtherInfoExists(OtherInfo info) {
		Query query = getCurrentSession().createQuery("from OtherInfo where otherName=? or account=?");
		query.setParameter(0, info.getOtherName());
		query.setParameter(1, info.getAccount());
		   if(query.list().size()>0){
			   return (OtherInfo)query.list().get(0);
		   }
		return null;
	}


	public String createOtherInfo(OtherInfo oldinfo, MultipartFile sjsj, String liveActionPath, MultipartFile yyzz,
			String licensePath, MultipartFile htxy, String deliverPath, MultipartFile card, String cardPath,OtherMoney money) {
         
		try {
			getCurrentSession().save(oldinfo);
			money.setOtherId(oldinfo.getId());
			getCurrentSession().save(money);
			sjsj.transferTo(new File(liveActionPath));
			yyzz.transferTo(new File(licensePath));
			htxy.transferTo(new File(deliverPath));
			card.transferTo(new File(cardPath));
			
			return "true";
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			e.printStackTrace();
			return "false";
		}
	}


	public List<SuperMarketInfo> getListSuper(Integer agentId) {
		Query query = getCurrentSession().createQuery("from SuperMarketInfo where agentId=:id");
		query.setParameter("id", agentId);
		return query.list();
	}


	public String updateAgentHotAndSuperEntrepot(AgentHot agentHot, List<SuperMarketEntrepot> entreList) {
		try {
			    getCurrentSession().update(agentHot);
			for (SuperMarketEntrepot superMarketEntrepot : entreList) {
				getCurrentSession().save(superMarketEntrepot);
			}			
			return "true";
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			e.printStackTrace();
			return "false";
		}

	}


	public AgentInfo getAgentInfoBytAccount(String account) {
		Query query = getCurrentSession().createQuery("from AgentInfo where account=:account");
		query.setParameter("account", account);
		return (AgentInfo)query.uniqueResult();
	}


	public AgentInfo getAgentInfoByagentRegionAndStatus(String agentRegion) {
		Query query = getCurrentSession().createQuery("from AgentInfo where agentRegion=:agentRegion and status=1");
		query.setParameter("agentRegion", agentRegion);
		return (AgentInfo) query.uniqueResult();
	}


	public String updateAgentInfo(AgentInfo info, BankAccount bank) {
		try {
			this.getCurrentSession().update(info);
			this.getCurrentSession().update(bank);
			return "true";
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			e.printStackTrace();
			return "false";
	   }
	}


	public String updateAgentInfoSaveBank(AgentInfo info, BankAccount bank) {
		try {
			this.getCurrentSession().update(info);
			this.getCurrentSession().save(bank);
			return "true";
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			e.printStackTrace();
			return "false";
	   }
	}


	public String updateAgentHotAndSuperEntrepot(AgentHot hot) {
		try {
			this.getCurrentSession().update(hot);
			Query query = getCurrentSession().createQuery("update SuperMarketEntrepot set putaway=:putaway where agentHotId=:agentHotId");
			query.setParameter("putaway", hot.getPutaway());
			query.setParameter("agentHotId", hot.getId());
			query.executeUpdate();
			return "true";
		} catch (Exception e) {
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			e.printStackTrace();
			return "false";
	   }
	}


	public List<AgentHot> getAgentHotsByAgentId(int agentId) {
		try {
			Query query = getCurrentSession().createQuery("from AgentHot where agentId=:agentId");
			query.setParameter("agentId", agentId);
			return query.list();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
	   }
	}
}
